# -*- coding: utf-8 -*-
"""
author:码同学 极光
date:2025/4/19
desc: 
sample: 
"""
from django.db.models import Q
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.validators import UniqueValidator

from apitest.models import UserInfo

#序列化 ，model
class UserInfoSerializer(serializers.ModelSerializer):
    name = serializers.CharField(min_length=2, max_length=32,
                                 error_messages={'min_length': '项目名称不能少于2位',
                                                 'max_length': '项目名称不能大于20'},
                                 validators=[UniqueValidator(queryset=UserInfo.objects.all(),message='名称不能重复')])
    is_adult = serializers.SerializerMethodField(label='是否成人', read_only=True) #不参写 只参与返回
    age = serializers.CharField(write_only=True)
    password = serializers.CharField(write_only=True) #不会参与返回

    def validate(self, attrs):
        print(attrs)
        #queryset = UserInfo.objects.filter(name=attrs['name'],password=attrs['password'])
        pw = attrs['password']
        name = attrs['name']
        users = UserInfo.objects.filter(Q(password=pw) | Q(name=name))
        if (users.exists()):
            raise ValidationError({'message': '名字或者密码都已经存在!'})
        return attrs

    def get_is_adult(self, obj):
        if obj.age >= 18:
            return '成年'
        else:
            return '未成年'

    # def validate_password(self, value):
    #     print(value)
    #     queryset = UserInfo.objects.filter(password=value)
    #     if (queryset.exists()):
    #         raise ValidationError({'message': '密码重复!', 'data': None})
    #     return value

    class Meta:
        model = UserInfo
        fields = '__all__'
        #fields = ('id', 'name')